package guowei.gulielasticsearch.service.impl;

import com.alibaba.fastjson.JSON;
import guowei.common.to.es.EsModel;
import guowei.gulielasticsearch.EsConstant.ProductConstant;
import guowei.gulielasticsearch.service.EsProductService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EsProductServiceImpl implements EsProductService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 学会批量操作保存es信息
     * @param esModels
     */
    @Override
    public void saveEsProducts(List<EsModel> esModels) {
        BulkRequest bulkRequest = new BulkRequest();
        for (EsModel esmode:esModels) {
            IndexRequest indexRequest = new IndexRequest(ProductConstant.PRODUCT_INDEX);
            indexRequest.id(esmode.getSkuId().toString());
            String s = JSON.toJSONString(esmode);
            indexRequest.source(s, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }
        try {
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
